import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { DragResult } from 'smooth-dnd'
import type { MaterialType } from '@/data-type/material.type'
import { ArrayUtils, CommonUtils, NumberUtils } from 'great-jsutils'

export const useMaterialInstanceStore = defineStore('materialInstance', () => {
  // 最外层的容器ID为null，子容器的ID为uuid的值，每次拖入时要发实例化的子容器、子组件设置uuid
  const parentContainerId = ref<any>()
  const mouseEnterMaterialInstanceId = ref<any>()
  const mouseDownMaterialInstanceId = ref<any>()
  const removedMaterial = ref<MaterialType|null>()
  const materialInstanceList = ref<MaterialType[]>([])
  const selectedMaterialInstanceId = ref<string | null | undefined>(null)
  const selectedMaterialInstance = computed(() => {
    return getSelectedMaterialInstance()
  });

  function setMouseEnterMaterialInstanceId(id: string | null) {
    const enterMaterial = ArrayUtils.get(materialInstanceList.value, id);
    if(['baseContainer'].includes(enterMaterial.type)){
      return;
    }
    mouseEnterMaterialInstanceId.value = id
  }

  function setMouseDownMaterialInstanceId( id: string | null) {
    const enterMaterial = ArrayUtils.get(materialInstanceList.value, id);
    mouseDownMaterialInstanceId.value = id
  }

  function setParentContainerId(id: string | null) {
    parentContainerId.value = id
  }

  function getSelectedMaterialInstance() {
    if (materialInstanceList.value && selectedMaterialInstanceId.value) {
      const material = ArrayUtils.get(materialInstanceList.value, selectedMaterialInstanceId.value)
      return material
    } else {
      return null
    }
  }

  function setSelectedMaterialInstanceId(material: MaterialType) {
    const id = material.id
    if (selectedMaterialInstanceId.value === id) {
      if (material.type == 'grid') {
        // grid时
      }
      //selectedMaterialInstanceId.value = null
    } else {
      selectedMaterialInstanceId.value = id
    }
  }

  function cacheMaterialInstance() {
    setTimeout(()=>{
      localStorage.setItem('ZT_MATERIAL_INSTANCE', JSON.stringify(materialInstanceList.value))
    }, 500);
  }

  function initMaterialInstanceList(dataList: MaterialType[]) {
    materialInstanceList.value = dataList
  }

  /**
   * @param arr: 物料实例集合
   * @param dragResult：被拖放的物料
   * @param parentId：当前物料所在容器ID（从此容器拖拽出去的）
   */
  const applyDrag = <T extends any[]>(arr: T, dragResult: DragResult, parentId: string) => {
    let result = [...arr]
    const { addedIndex, removedIndex, payload } = dragResult;
    console.log({addedIndex, removedIndex, payload, parentId, removeMaterial: removedMaterial.value});
    const parentMaterial = parentId?ArrayUtils.get(materialInstanceList.value, parentId):null;
    const mouseEnterMaterial = mouseEnterMaterialInstanceId.value?ArrayUtils.get(materialInstanceList.value, mouseEnterMaterialInstanceId.value):null;
    const selectedMaterial = selectedMaterialInstanceId.value?ArrayUtils.get(materialInstanceList.value, selectedMaterialInstanceId.value):null;
    const mouseDownMaterial = selectedMaterialInstanceId.value?ArrayUtils.get(materialInstanceList.value, mouseDownMaterialInstanceId.value):null;
    //console.log('parentMaterial: ', parentMaterial);
    //console.log('mouseEnterMaterial: ', mouseEnterMaterial);
    //console.log('selectedMaterial: ', selectedMaterial);
    //console.log('mouseDownMaterial: ', mouseDownMaterial);
    if (isNumber(addedIndex)) {
      // 这是添加
      if (payload) {
        const newPayload = JSON.parse(JSON.stringify(payload))
        newPayload.id = CommonUtils.uuid()
        if (parentId) {
          // 从物料库向子容器中添加
          newPayload.parentId = parentId
          console.log('从物料库向子容器中添加');
          ArrayUtils.add(result, newPayload)
        } else {
          // 从物料库向父容器中添加
          addMaterialTool(result, addedIndex, newPayload);
        }
      } else if (isNumber(removedIndex)&&!parentId) {
        // 这是根容器内拖拽修改位置
        const newArray = arrayMove(materialInstanceList.value, removedIndex, addedIndex)
        console.log('这是根容器内拖拽修改位置');
        result = [...newArray]
      }else if(isNumber(removedIndex)&&parentId){// 这是子容器内拖拽修改位置
        console.log('这是子容器内拖拽修改位置');
        let childrenMaterial = parentMaterial.children;
        const newArray = arrayMove(childrenMaterial, removedIndex, addedIndex);
        childrenMaterial = [...newArray];
        parentMaterial.children = childrenMaterial;
      }else if(parentId){
        console.log('从其他容器拖放：', removedMaterial.value, parentMaterial);
        if(removedMaterial.value){
          removedMaterial.value.id=CommonUtils.uuid();
          parentMaterial.children = parentMaterial.children?[...parentMaterial.children, removedMaterial.value]:[removedMaterial.value];
          removedMaterial.value = null;
        }
      }else{
        console.log('----其他情况。。。');
        if(removedMaterial.value){
          removedMaterial.value.id=CommonUtils.uuid();
          removedMaterial.parentId = null;
          result.push(removedMaterial.value);
          removedMaterial.value = null;
        }
      }
    } else if (isNumber(removedIndex)) {
      if (parentId) {
        console.log('这是子容器拖出物料');
        const childrenMaterial = parentMaterial.children;
        removeMaterialTool(childrenMaterial, removedIndex);
        parentMaterial.children = childrenMaterial;
      } else {
        // 从父容器拖放到子容器
        console.log('从父容器拖放到子容器!');
        const dragMaterial = materialInstanceList.value[removedIndex]
        removeMaterialTool(result, removedIndex);
        if(parentContainerId.value){
          const containerMaterial = ArrayUtils.get(
              materialInstanceList.value, parentContainerId.value
          );
          console.log(dragMaterial, 'containerMaterial从其他容器拖放到了——>',containerMaterial);
          dragMaterial.id = CommonUtils.uuid();
          dragMaterial.parentId = containerMaterial.id;
          containerMaterial.children = containerMaterial.children?[...containerMaterial.children]:[];
          containerMaterial.children = [...containerMaterial.children, dragMaterial];
        }
      }
    }
    cacheMaterialInstance()
    return result
  }
  const applyDrag1 = <T extends any[]>(arr: T, dragResult: DragResult, parentId: string) => {
    const result = [...arr]
    const { addedIndex, removedIndex, payload } = dragResult
    console.log({ addedIndex, removedIndex, payload, parentId })
    // 从子容器拖出
    if (parentId && removedIndex !== null && !payload) {
      const material = ArrayUtils.get(materialInstanceList.value, parentId)
      if (addedIndex === null) {
        if (material && material.children && material.children.length > 0) {
          removeMaterialTool(material.children, removedIndex);
        }
      } else if (addedIndex !== null) {
        const newChildren = arrayMove(material.children, removedIndex, addedIndex)
        material.children = newChildren
      }
      // 从子容器拖出放进父容器
    } else if (addedIndex !== null && !payload && parentId) {
      const material = ArrayUtils.get(
        materialInstanceList.value,
        mouseEnterMaterialInstanceId.value
      )
      if (material) {
        if (parentId) {
          material.parentId = parentId
          // ArrayUtils.add(result, material);
        } else {
          material.parentId = null
          addMaterialTool(result, addedIndex, material);
        }
      }
    } else if (parentContainerId.value) {
      if (parentId === parentContainerId.value) {
        // 这是添加，也就是从外面拖入
        if (addedIndex !== null && removedIndex === null && payload) {
          const newPayload = JSON.parse(JSON.stringify(payload))
          newPayload.id = CommonUtils.uuid()
          newPayload.isInstance = true
          newPayload.parentId = parentContainerId.value
          ArrayUtils.add(result, newPayload)
        }
      }
    } else {
      // 这是添加，也就是从外面拖入
      if (addedIndex !== null && removedIndex === null && payload) {
        const newPayload = JSON.parse(JSON.stringify(payload))
        newPayload.id = CommonUtils.uuid()
        addMaterialTool(result, addedIndex, newPayload);
      }
      // 这是移动，也就是在当前容器内拖动改变顺序
      else if (addedIndex !== null && removedIndex !== null) {
        arrayMove(materialInstanceList.value, removedIndex, addedIndex)
      }
      // 这是删除
      else if (addedIndex === null && removedIndex !== null && result.length > 0) {
        removeMaterialTool(result, removedIndex);
      }
    }
    cacheMaterialInstance()
    return result
  }

  /**
   * 整体替换
   * @param Materials
   */
  function replaceAll(newMaterials: []) {
    materialInstanceList.value = [...newMaterials]
  }

  function removeMaterialTool(array: any[], removeIndex: number){
    //useMaterialInstanceStore.setMouseDownMaterialInstanceId('ss');
    removedMaterial.value = array[removeIndex];
    array.splice(removeIndex, 1)
  }

  return {
    materialInstanceList,
    selectedMaterialInstance,
    selectedMaterialInstanceId,
    initMaterialInstanceList,
    setSelectedMaterialInstanceId,
    replaceAll,
    applyDrag,
    setParentContainerId,
    mouseEnterMaterialInstanceId,
    setMouseDownMaterialInstanceId,
    setMouseEnterMaterialInstanceId
  }
})

function arrayMove<T>(array: T[], from: number, to: number): T[] {
  const newArray = array.slice()
  newArray.splice(to < 0 ? newArray.length + to : to, 0, newArray.splice(from, 1)[0])
  return newArray
}

function isNumber(num: any) {
  return /\d+/.test(num)
}
function addMaterialTool(array: any[], addedIndex: number, payload: any){
  array.splice(addedIndex, 0, payload)
}
